package com.leizi.igym.controller.user;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leizi.igym.constant.CourseConstant;
import com.leizi.igym.domain.Plan;
import com.leizi.igym.domain.Post;
import com.leizi.igym.domain.User;
import com.leizi.igym.dto.*;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.resp.Result;
import com.leizi.igym.service.CourseService;
import com.leizi.igym.service.PlanService;
import com.leizi.igym.service.PostService;
import com.leizi.igym.utils.ThrowUtils;
import com.leizi.igym.vo.PostVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-05  17:48
 * @Description:
 */

@RestController("userPostController")
@RequestMapping("/user/post")
@Tag(name = "用户端-帖子相关接口")
@Slf4j
public class PostController {

    @Resource
    private PostService postService;

    @Operation(summary = "用户端：新增帖子")
    @PostMapping
    public Result add(@RequestBody PostAddDTO dto) {
        log.info("用户端正在添加帖子信息，帖子信息为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        boolean result = postService.add(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.OPERATION_ERROR, "添加帖子失败！");
        }
        return Result.ok(true);
    }

    @Operation(summary = "用户端：删除帖子信息")
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") Long id) {
        log.info("用户端正在删除帖子信息，帖子id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0, ReturnCodeEnum.PARAMS_ERROR);
        boolean result = postService.deleteWithES(id);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除帖子失败！");
        }
        return Result.ok(true);
    }

    // @Operation(summary = "用户端：批量删除帖子信息")
    // @DeleteMapping("batch")
    // public Result deleteBatch(@RequestBody List<Long> ids) {
    //     log.info("用户端正在批量删除帖子信息，帖子们的id为：{}", ids);
    //     ThrowUtils.throwIf(CollectionUtil.isEmpty(ids), ReturnCodeEnum.PARAMS_ERROR);
    //     boolean result = courseService.deleteTrainerBatchInAdmin(ids);
    //     if (!result) {
    //         throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "删除教练信息失败！");
    //     }
    //     return Result.ok(result);
    // }

    @Operation(summary = "用户端：修改帖子信息")
    @PutMapping("{id}")
    public Result update(@PathVariable("id") Long id, @RequestBody PostDTO dto) {
        log.info("用户端正在修改帖子信息，id为：{}，修改帖子为：{}", id, dto);
        ThrowUtils.throwIf(Objects.isNull(dto) ||
                        id == null ||
                        id <= 0 ||
                        !id.equals(dto.getId()),
                ReturnCodeEnum.PARAMS_ERROR);
        boolean result = postService.updateAndToES(dto);
        if (!result) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "修改教练信息失败！");
        }
        return Result.ok(true);
    }


    @Operation(summary = "用户端：根据id查询帖子信息")
    @GetMapping("{id}")
    public Result<PostVO> getById(@PathVariable("id") Long id) {
        log.info("用户端正在根据id查询帖子信息，id为：{}", id);
        ThrowUtils.throwIf(Objects.isNull(id) || id <= 0,
                ReturnCodeEnum.PARAMS_ERROR);

        PostVO postVO = postService.getByIdWithUserInfo(id);
        if (Objects.isNull(postVO)) {
            throw new BusinessException(ReturnCodeEnum.NOT_FOUND_ERROR, "该帖子不存在！");
        }
        return Result.ok(postVO);
    }


    // @Operation(summary = "用户端：根据用户id查询帖子信息")
    // @GetMapping("/user/{userId}")
    // public Result<List<Plan>> getByUserId(@PathVariable("userId") Long userId) {
    //     log.info("用户端正在查询自己所有帖子信息，用户id为：{}", userId);
    //     ThrowUtils.throwIf(Objects.isNull(userId) || userId <= 0,
    //             ReturnCodeEnum.PARAMS_ERROR);
    //
    //     List<Plan> planList = planService.getPlanByUserId(userId);
    //     if (CollectionUtil.isEmpty(planList)) {
    //         throw new BusinessException(ReturnCodeEnum.NOT_FOUND_ERROR, "未找到该用户的帖子！");
    //     }
    //     return Result.ok(planList);
    // }

    @Operation(summary = "用户端：全文搜索帖子")
    @GetMapping("search")
    public Result<List<PostVO>> searchPost(PostSearchDTO dto) throws IOException {
        log.info("用户端正在全文查询自己帖子信息，搜索文本为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto),
                ReturnCodeEnum.PARAMS_ERROR);
        List<PostVO> postVOList = postService.getBySearch(dto);
        return Result.ok(postVOList);
    }

    @Operation(summary = "用户端：帖子点赞操作")
    @PutMapping("/like/{id}")
    public Result doLike(@PathVariable("id") Long id, @RequestBody PostLikeDTO dto) {
        if (ObjectUtils.anyNull(id, dto) || id < 0 ) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }
        boolean result = postService.doLike(id, dto);
        if (!result) {
            return Result.fail(ReturnCodeEnum.UPDATE_ERROR, "点赞相关操作失败！");
        }
        return Result.ok(true);
    }

    @Operation(summary = "用户端：帖子收藏操作")
    @PutMapping("/collect/{id}")
    public Result doCollect(@PathVariable("id") Long id, @RequestBody PostCollectDTO dto) {
        if (ObjectUtils.anyNull(id, dto) || id < 0 ) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }
        boolean result = postService.doCollect(id, dto);
        if (!result) {
            return Result.fail(ReturnCodeEnum.UPDATE_ERROR, "收藏相关操作失败！");
        }
        return Result.ok(true);
    }

    @Operation(summary = "用户端：我的帖子")
    @GetMapping("my")
    public Result<List<PostVO>> myPost(@RequestParam("userId") Long userId) {
        log.info("用户端正在查询自己帖子信息，查询用户id为：{}", userId);
        ThrowUtils.throwIf(Objects.isNull(userId),
                ReturnCodeEnum.PARAMS_ERROR);
        List<PostVO> postVOList = postService.getMy(userId);
        return Result.ok(postVOList);
    }

    @Operation(summary = "用户端：我的帖子数量")
    @GetMapping("myCount")
    public Result myPostCount(@RequestParam("userId") Long userId) {
        log.info("用户端正在查询自己帖子的条数，查询用户id为：{}", userId);
        ThrowUtils.throwIf(Objects.isNull(userId),
                ReturnCodeEnum.PARAMS_ERROR);
        QueryWrapper<Post> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        qw.eq("deleted",0);
        long count = postService.count(qw);
        return Result.ok(count);
    }

    @Operation(summary = "用户端：我的帖子数量")
    @GetMapping("likeCount")
    public Result myLikeCount(@RequestParam("userId") Long userId) {
        log.info("用户端正在查询自己点赞帖子的条数，查询用户id为：{}", userId);
        ThrowUtils.throwIf(Objects.isNull(userId),
                ReturnCodeEnum.PARAMS_ERROR);
        Integer count = postService.likeCount(userId);
        return Result.ok(count);
    }

    @Operation(summary = "用户端：我的帖子数量")
    @GetMapping("collectCount")
    public Result myCollectCount(@RequestParam("userId") Long userId) {
        log.info("用户端正在查询自己收藏帖子的条数，查询用户id为：{}", userId);
        ThrowUtils.throwIf(Objects.isNull(userId),
                ReturnCodeEnum.PARAMS_ERROR);
        Integer count = postService.collectCount(userId);
        return Result.ok(count);
    }
}
